/**
 * @author KdZhao/dongwenzhao@lngtop.com
 * @date 2020-12-8 10:29:25
 * @Description: vue离开/刷新当前页面时，若有未保存数据，提示用户是否离开？
 */

export default {
    data () {
        return {
            isEdit: false,
            pageCount: 0
        };
    },
    beforeRouteLeave (to, from, next) {
        // 导航离开该组件的对应路由时调用
        if (this.isEdit) {
            this.$confirm('当前页面数据未保存，确定要离开？', '提示', { type: 'warning' })
                .then(() => {
                    next();
                })
                .catch(() => {
                    next(false);
                });
        } else {
            next();
        }
    },
    methods: {
        beforeunloadFn (e) {
            if (this.isEdit) {
                e = e || window.event;
                // 兼容IE8和Firefox 4之前的版本
                if (e) {
                    e.returnValue = '关闭提示';
                }
                // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
                return '关闭提示';
            }
        }
    },

    mounted () {
        window.addEventListener('beforeunload', e => this.beforeunloadFn(e));
    },
    destroyed () {
        window.removeEventListener('beforeunload', e => this.beforeunloadFn(e));
    }
};
